package com.qiaofang.applet.rest;

import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.dto.PageDataRequest;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.constants.PropertyImageConstants;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.service.EmployeePropertyService;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.dto.EmployeeListDto;
import com.qiaofang.applet.service.member.service.dto.EmployeePropertyQueryDto;
import com.qiaofang.applet.service.member.service.mapstruct.EmployeeMapper;
import com.qiaofang.applet.service.property.domain.Estate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.domain.PropertyVideo;
import com.qiaofang.applet.service.property.domain.PropertyVr;
import com.qiaofang.applet.service.property.service.*;
import com.qiaofang.applet.service.property.service.dto.*;
import com.qiaofang.applet.service.property.service.mapstruct.EstateMapper;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyMapper;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyVideoMapper;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyVrMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/web/rentProperty")
@Api(tags = "房源：租房模块")
public class RentPropertyController {

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private PropertyVrService propertyVrService;

    @Autowired
    private PropertyVideoService propertyVideoService;

    @Autowired
    private EstateService estateService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private PropertyVrMapper propertyVrMapper;

    @Autowired
    private PropertyVideoMapper propertyVideoMapper;

    @Autowired
    private EstateMapper estateMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeePropertyService employeePropertyService;


    @PostMapping("/searchRentProperty")
    @ApiOperation(value = "查询租房列表", notes = "查询租房列表")
    public DataResponse<Page<RentPropertyListDto>> searchRentProperty(@RequestBody @Valid PageDataRequest<RentPropertyQueryDto> request) {
        if (StringUtils.isBlank(request.getParam().getCityCode())) {
            throw new BusinessException("请先选择城市");
        }

        // 经纪人主页选房源查询-排除经纪人已选房源
        if (StringUtils.isNotBlank(request.getParam().getEmployeeUniqueUuid())) {
            EmployeePropertyQueryDto queryDto = new EmployeePropertyQueryDto();
            queryDto.setEmployeeUniqueUuid(request.getParam().getEmployeeUniqueUuid());
            queryDto.setPropertyType(BusinessConstants.RENT_PROPERTY.getValue());
            List<String> uuidList = employeePropertyService.findPropertyListByParams(queryDto);
            request.getParam().setNotPropertyUniqueUuids(uuidList);
        }

        request.getParam().setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

        Page<Property> propertyPage = propertyService.findAllRentByParams(request.getParam(), PageUtil.getPageable(request));

        Page<RentPropertyListDto> result = propertyMapper.convertDomainToRentListDto(propertyPage);

        return DataResponse.ok(result);
    }

    @PostMapping("/searchSameRentProperty")
    @ApiOperation(value = "查询同城市同小区/同房型二手房列表", notes = "查询同城市同小区/同房型二手房列表")
    public DataResponse<Page<RentPropertyListDto>> searchSameRentProperty(@RequestBody @Valid PageDataRequest<PropertySameDto> request) {
        Page<RentPropertyListDto> result = null;

        Property property = propertyService.findByPropertyUniqueUuid(request.getParam().getPropertyUniqueUuid());

        if (property != null) {
            RentPropertyQueryDto queryDto = new RentPropertyQueryDto();
            queryDto.setCityCode(property.getCityCode());
            queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

            if (request.getParam().getSameFlag() == 1) {
                queryDto.setEstateUniqueUuid(property.getEstateUniqueUuid());
            } else {
                queryDto.setCountF(property.getCountF());
            }

            Page<Property> propertyPage = propertyService.findSameRentByParams(property.getPropertyUniqueUuid(), queryDto, PageUtil.getPageable(request));
            result = propertyMapper.convertDomainToRentListDto(propertyPage);
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/getRentProperty")
    @ApiOperation(value = "租房详情", notes = "租房详情")
    public DataResponse<RentPropertyDetailDto> getRentProperty(@RequestBody @Valid DataRequest<PropertyDetailQueryDto> request) {
        RentPropertyDetailDto result = null;

        Property property = propertyService.findByPropertyUniqueUuid(request.getParam().getPropertyUniqueUuid());

        if (property != null) {
            result = propertyMapper.domainToRentDetailDto(property);

            List<PropertyImageDto> propertyImageDtoList = new ArrayList<>();

            // 处理Vr图片
            PropertyVr propertyVr = propertyVrService.findByPropertyUuidAndCityCode(property.getPropertyUuid(), property.getCityCode());

            if (propertyVr != null) {
                propertyImageDtoList.add(propertyVrMapper.domainToImageDto(propertyVr));
            }

            // 处理视频图片
            PropertyVideo propertyVideo = propertyVideoService.findByPropertyUuidAndCityCode(property.getPropertyUuid(), property.getCityCode());

            if (propertyVideo != null) {
                propertyImageDtoList.add(propertyVideoMapper.domainToImageDto(propertyVideo));
            }

            //处理其余图片
            if (!CollectionUtils.isEmpty(property.getImageUrls())) {
                for (String imageUrl : property.getImageUrls()) {
                    PropertyImageDto imageDto = new PropertyImageDto();
                    imageDto.setImgUrl(imageUrl);
                    imageDto.setImageType(PropertyImageConstants.IMAGE_TYPE.getValue());
                    propertyImageDtoList.add(imageDto);
                }
            }

            //查询楼盘
            Estate estate = estateService.findByEstateUniqueUuid(property.getEstateUniqueUuid());

            EstateDetailDto estateDetailDto = estateMapper.domainToDetailDto(estate);

            // 经纪人主页详情
            if (StringUtils.isNotBlank(request.getParam().getEmployeeUniqueUuid())) {

                Employee employee = employeeService.findByEmployeeUniqueUuid(request.getParam().getEmployeeUniqueUuid());

                result.setEmployeeListDto(employeeService.domainToListDto(employee));

                // 普通详情
            } else {
                List<EmployeeListDto> employeeListDtoList = employeeService.getEmployeeListDtoByPropety(property);

                if (!CollectionUtils.isEmpty(employeeListDtoList)) {
                    for (EmployeeListDto employeeListDto : employeeListDtoList) {
                        if (employeeListDto.getEmployeeUuid().equals(property.getEmployeeUuid1())) {
                            result.setEmployeeListDto(employeeListDto);
                        }
                    }
                }

                result.setEmployeeListDtos(employeeListDtoList);
            }

            result.setPropertyImageDtoList(propertyImageDtoList);
            result.setEstateDetailDto(estateDetailDto);
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/getRentPropertyV1")
    @ApiOperation(value = "租房详情", notes = "租房详情")
    public DataResponse<RentPropertyDetailDto> getRentPropertyV1(@RequestBody @Valid DataRequest<PropertyDetailQueryDto> request) {
        RentPropertyDetailDto result = null;

        Property property = propertyService.findByPropertyUniqueUuid(request.getParam().getPropertyUniqueUuid());

        if (property != null) {
            result = propertyMapper.domainToRentDetailDto(property);

            List<PropertyImageDto> propertyImageDtoList = new ArrayList<>();

            // 处理Vr图片
            PropertyVr propertyVr = propertyVrService.findByPropertyUuidAndCityCode(property.getPropertyUuid(), property.getCityCode());

            if (propertyVr != null) {
                propertyImageDtoList.add(propertyVrMapper.domainToImageDto(propertyVr));
            }

            // 处理视频图片
            PropertyVideo propertyVideo = propertyVideoService.findByPropertyUuidAndCityCode(property.getPropertyUuid(), property.getCityCode());

            if (propertyVideo != null) {
                propertyImageDtoList.add(propertyVideoMapper.domainToImageDto(propertyVideo));
            }

            //处理其余图片
            if (!CollectionUtils.isEmpty(property.getImageUrls())) {
                for (String imageUrl : property.getImageUrls()) {
                    PropertyImageDto imageDto = new PropertyImageDto();
                    imageDto.setImgUrl(imageUrl);
                    imageDto.setImageType(PropertyImageConstants.IMAGE_TYPE.getValue());
                    propertyImageDtoList.add(imageDto);
                }
            }

            //查询楼盘
            Estate estate = estateService.findByEstateUniqueUuid(property.getEstateUniqueUuid());

            EstateDetailDto estateDetailDto = null;
            if (Objects.nonNull(estate)) {
                estateDetailDto = estateMapper.domainToDetailDto(estate);
            }else {
                estateDetailDto = new EstateDetailDto();
                estateDetailDto.setLng(property.getLng());
                estateDetailDto.setLat(property.getLat());
            }
            //百度地图坐标系转换成腾讯坐标系
            if (estateDetailDto.getLat() != null && estateDetailDto.getLng() != null) {
                double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
                double x = estateDetailDto.getLng() - 0.0065;
                double y = estateDetailDto.getLat() - 0.006;
                double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
                double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
                estateDetailDto.setLat(z * Math.sin(theta));
                estateDetailDto.setLng(z * Math.cos(theta));
            }
            result.setEstateDetailDto(estateDetailDto);
            result.setPropertyImageDtoList(propertyService.dealPropertyImgWaterMark(propertyImageDtoList, property.getPropertyUniqueUuid(), property.getCompanyUuid()));
        }

        return DataResponse.ok(result);
    }

    @PostMapping("/getPropertyShowEmp")
    @ApiOperation(value = "获取房源经纪人", notes = "获取房源经纪人")
    public DataResponse<PropertyEmpDto> getPropertyShowEmp(@RequestBody @Valid DataRequest<PropertyDetailQueryDto> request) {
        PropertyEmpDto result = new PropertyEmpDto();
        if (StringUtils.isNotBlank(request.getParam().getEmployeeUniqueUuid())) {
            Employee employee = employeeService.findByEmployeeUniqueUuid(request.getParam().getEmployeeUniqueUuid());
            result.setEmployeeListDto(employeeService.domainToListDto(employee));
            if (request.getParam().isShowEmpList()) {
                result.setEmployeeListDtos(employeeService.getEmployeeDtoByProperty(request.getParam().getPropertyUniqueUuid()).getEmployeeListDtos());
            }
        }else {
            result = employeeService.getEmployeeDtoByProperty(request.getParam().getPropertyUniqueUuid());
        }

        return DataResponse.ok(result);
    }
}
